package cn.yangliu.shiro.web;

import cn.yangliu.comm.CommConst;
import cn.yangliu.comm.entity.JsonResult;
import cn.yangliu.comm.tools.StringUtils;
import cn.yangliu.comm.tools.WebUtils;
import cn.yangliu.shiro.ShiroConst;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 作者 杨柳
 * 创建时间 2017-08-25 02:39
 */
@Controller
public class ShiroLoginController extends AbstractController {

//    @RequestMapping(value = ShiroConst.LOGIN_URL,method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView login(HttpServletRequest request,HttpServletResponse response) {
        String msg = (String) request.getAttribute(ShiroConst.LOGIN_ERROR_KEY);
        if (WebUtils.checkJsonAjax()){
            JsonResult result = new JsonResult();
            if (StringUtils.isEmpty(msg)){
                msg = "请先登录!";
            }
            result.setMsg(msg);
            result.setCode(CommConst.LOGIN_ERROR_CODE);
            WebUtils.printData(result,response);
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()){
            return new ModelAndView("redirect:"+ShiroConst.SUCCESS_URL);
        }
        ModelAndView mav = new ModelAndView(ShiroConst.LOGIN_VIEW);
        //不用每次都输入用户名
        mav.addObject(ShiroConst.USERNAME_PARAM, request.getParameter(ShiroConst.USERNAME_PARAM));
        mav.addObject(ShiroConst.PASSWORD_PARAM, request.getParameter(ShiroConst.PASSWORD_PARAM));
        return mav;
    }



    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return login(request,response);
    }
}
